import React, { useState } from "react";
import Menu, { Item as MenuItem } from "rc-menu";
import type { SelectInfo } from "rc-menu/lib/interface";
import DropDown from "rc-dropdown";
import classnames from "classnames";
import { prefixCls as baseCls } from "../constant";

type Options = Array<{
  value: string | number;
  label: string;
}>;

type OverLayProps = {
  options: Options;
  selectedKey?: string;
  onSelect: (info: SelectInfo) => void;
};

const OverLay: React.FC<OverLayProps> = (props) => {
  return (
    <Menu
      prefixCls={`${baseCls}-size-changer-menu`}
      className="dropdown-menu"
      onSelect={props.onSelect}
      selectedKeys={[]}
    >
      {props.options?.map((option, index) => (
        <MenuItem className="menu-item" key={option.value}>
          {option.label}
        </MenuItem>
      ))}
    </Menu>
  );
};

const getLabel = (value: any, options: Options) => {
  let ans = options[0].label;
  options.forEach((option, index) => {
    if (option.value == value) {
      ans = option.label;
    }
  });

  return ans;
};

const prefixCls = `${baseCls}-size-changer`;

export default function SizeChanger({
  options,
  className,
  value,
  onChange,
}: {
  options: Options;
  className: string;
  value: string;
  onChange: (value: any) => void;
}) {
  const [visible, setVisible] = useState(false);

  return (
    <DropDown
      arrow={true}
      prefixCls={prefixCls}
      overlay={
        <OverLay
          options={options}
          onSelect={(info: SelectInfo) => {
            onChange(info.key);
            setVisible(false);
          }}
        />
      }
      getPopupContainer={(node) => node.parentElement!}
      animation="slide-up"
      visible={visible}
      onVisibleChange={setVisible}
      trigger="click"
    >
      <div className={classnames(prefixCls + "-selector", className)}>
        <span className="text">{getLabel(value, options)}</span>
        <span
          className={classnames(
            visible && `${baseCls}-size-changer-arrow-open`,
            `${baseCls}-size-changer-arrow`
          )}
        />
      </div>
    </DropDown>
  );
}
